package com.chukun.gateway.core.container;

import com.chukun.gateway.core.config.GatewayConfig;
import com.chukun.gateway.core.life.LifeCycle;
import com.chukun.gateway.core.netty.client.NettyHttpClient;
import com.chukun.gateway.core.netty.server.NettyHttpServer;
import com.chukun.gateway.core.processor.DisruptorNettyCoreProcessor;
import com.chukun.gateway.core.processor.NettyCoreProcessor;
import com.chukun.gateway.core.processor.NettyProcessor;
import lombok.extern.slf4j.Slf4j;

import static com.chukun.gateway.common.constants.GatewayConst.BUFFER_TYPE_PARALLEL;

/**
 * @author chukun
 * @version 1.0.0
 * @description 容器的加载类
 * @createTime 2023/11/25 22:00
 */
@Slf4j
public class Container implements LifeCycle {

    private final GatewayConfig config;

    private NettyHttpServer nettyHttpServer;

    private NettyHttpClient nettyHttpClient;

    private NettyProcessor nettyProcessor;

    public Container(GatewayConfig config) {
        this.config = config;
        init();
    }


    @Override
    public void init() {
        NettyCoreProcessor nettyCoreProcessor = new NettyCoreProcessor();
        if (BUFFER_TYPE_PARALLEL.equals(config.getBufferType())) {
            this.nettyProcessor = new DisruptorNettyCoreProcessor(this.config, nettyCoreProcessor);
        } else {
            this.nettyProcessor = nettyCoreProcessor;
        }
        this.nettyHttpServer = new NettyHttpServer(config, nettyProcessor);

        this.nettyHttpClient = new NettyHttpClient(config, nettyHttpServer.getWorkerEventLoopGroup());
    }

    @Override
    public void start() {
        nettyHttpServer.start();;
        nettyHttpClient.start();
        log.info("api gateway started!");
    }

    @Override
    public void shutdown() {
        nettyHttpServer.shutdown();
        nettyHttpClient.shutdown();
    }
}
